package com.aioz.security.service.impl;

import com.aioz.security.common.ResponseResult;
import com.aioz.security.entity.Follow;
import com.aioz.security.entity.LoginUser;
import com.aioz.security.mapper.FollowMapper;
import com.aioz.security.service.FollowService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Aioz
 * @since 2022-10-28
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {


    @Override
    public ResponseResult follow(Integer companyId, Boolean isFollow) {
        // 获取登录用户Id
        Integer userId = Math.toIntExact(getCurrentUserId());
        //判断到底是关注还是取关
        if(isFollow){
            //关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setCompanyId(companyId);
            save(follow);
            return new ResponseResult<>(200,"关注成功！");
        }else {
            //取关，删除
            remove(new QueryWrapper<Follow>()
                    .eq("user_id",userId).eq("company_id",companyId));
            return new ResponseResult<>(200,"取关成功！");
        }
    }

    @Override
    public ResponseResult isFollow(Integer companyId) {
        // 获取登录用户Id
        Integer userId = Math.toIntExact(getCurrentUserId());
        //查询是否关注
        Integer count = query().eq("user_id", userId).eq("company_id", companyId).count();
        //判断是否关注
        if(count > 0){
            return new ResponseResult<>(200,"已关注");
        }
        return new ResponseResult<>(200,"未关注");
    }

    public Long getCurrentUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }
}
